package main

import (
	"fmt"
	"github.com/sciter-sdk/go-sciter"
	"github.com/sciter-sdk/go-sciter/window"
	"io/ioutil"
	"log"
	"strconv"
)

// 加载资源
func main() {
	w, err := window.New(sciter.DefaultWindowCreateFlag, sciter.DefaultRect)
	if err != nil {
		log.Fatal(err)
	}
	// 加载文件
	str_bytes, err := ioutil.ReadFile("demo5/demo5.html")
	if err != nil {
		log.Fatal(err)
	}
	w.LoadHtml(string(str_bytes), "")
	w.SetTitle("元素加载内容")
	root, _ := w.GetRootElement()
	// 元素加载资源
	load(root)
	w.Show()
	w.Run()
}

func load(root *sciter.Element) {
	frame, _ := root.SelectById("frame")
	// load()类似jquery, 用于给元素加载指定内容
	// 加载html内容
	//RT_DATA_HTML = remote html data
	frame.AttachEventHandler(&sciter.EventHandler{
		OnDataArrived: func(he *sciter.Element, params *sciter.DataArrivedParams) bool {
			log.Println("iframe loaded: " + string(params.Data()))
			root_height, _ := root.Style("height")
			log.Println("root_height = " + root_height)
			he.SetStyle("height", "")
			log.Println("set height!!!!!")
			return false
		},
		OnAttached: func(he *sciter.Element) {

		},
	})

	root.AttachEventHandler(&sciter.EventHandler{
		OnSize: func(he *sciter.Element) {
			// 动态调整iframe，让其height=50%; style中的设置百分比不起作用；
			// 在tiscript中定义height函数返回元素高度
			root_height, _ := root.CallMethod("height")
			log.Println("root_height = " + root_height.String())
			frame_height := root_height.Int() / 2
			frame.SetStyle("height", strconv.Itoa(frame_height)+"px")
		},
	})
	frame.Load("http://www.qq.com", sciter.RT_DATA_HTML)
	log.Println(frame.Html(true))
	txt, _ := root.SelectById("txt")
	// 附加元素时间处理
	txt.AttachEventHandler(&sciter.EventHandler{
		// 当资源被加载, 但未使用时调用
		// 返回true: 取消资源使用
		// 返回false: 遵循正常过程
		OnDataArrived: func(he *sciter.Element, params *sciter.DataArrivedParams) bool {
			// 设置元素html
			he.SetHtml(string(params.Data()), sciter.SIH_REPLACE_CONTENT)
			log.Println("txt loaded: " + string(params.Data()))
			return false
		},
	})
	// 加载本地资源
	// 使用 `file:///C:/P/go/src/gitee.com/felix_huang/go-sciter-demo.git/demo5/testdata.txt`加载失败， 原因未知
	txt.Load("C:/P/go/src/gitee.com/felix_huang/go-sciter-demo.git/demo5/testdata.txt", sciter.RT_DATA_RAW)
	img, _ := root.SelectById("img")
	img.AttachEventHandler(&sciter.EventHandler{
		OnDataArrived: func(he *sciter.Element, params *sciter.DataArrivedParams) bool {
			he.SetAttr("src", params.Uri())
			log.Println("img loaded: " + params.Uri())

			return false
		},
	})
	img.Load("file://C:/P/go/src/gitee.com/felix_huang/go-sciter-demo.git/demo5/testpng.PNG", sciter.RT_DATA_IMAGE)

	// 加载脚本资源
	script, _ := root.SelectById("script")
	script.AttachEventHandler(&sciter.EventHandler{
		OnDataArrived: func(he *sciter.Element, params *sciter.DataArrivedParams) bool {
			fmt.Println(string(params.Data()))
			return false
		},
	})
	script.Load("http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js", sciter.RT_DATA_SCRIPT)

}
